<template>
  <div class="main-header flex align-center">
    <div class="logo flex align-center" style="min-width: 200px" @click="$router.push('/')">
      <div class="sysLogo flex-1" />
      <span class="home_btn" :class="$route.name === 'HOME' ? 'homeActive' : ''">{{
        $t('HOME')
      }}</span>
    </div>
    <!--菜单-->
    <topbar class="flex-1" />
    <div class="userinfo flex align-center justify-between pb-20" style="min-width: 260px">
      <span v-if="showIot" class="device_btn block" @click="iot">{{
        $t('MENU_DEVICE_MANAGER')
      }}</span>
      <el-menu
        ref="topNavMenu"
        mode="horizontal"
        background-color="#030F30"
        text-color="#FFFFFF"
        active-text-color="#fff"
        default-active=""
        unique-opened
        router
        class="flex justify-end"
      >
        <el-submenu index="user" popper-class="user-menu">
          <template v-slot:title>
            <div class="relative no-wrap">
              <el-avatar size="small" :src="defaultAvatar" />
              <el-badge v-if="getSysNoticeCount > 0" is-dot class="sys-notice" />
              <span class="user-name" :title="getUserId">
                {{ getUserId }}
              </span>
              <div v-if="licenseValidDays" class="license-expires">
                {{ licenseValidDays }}
              </div>
            </div>
          </template>
          <el-menu-item @click="infoShow = true">{{ $t('USER_INFO') }}</el-menu-item>
          <el-menu-item @click="pwdShow = true">{{ $t('MOD_PWD') }}</el-menu-item>
          <el-menu-item @click="authorizationShow = true">{{
            $t('AUTHORIZATION_INFO')
          }}</el-menu-item>
          <el-menu-item index="/message">
            <el-badge
              v-if="getSysNoticeCount > 0"
              :value="getSysNoticeCount"
              :max="99"
              class="item"
            >
              {{ $t('SYSTEM_NOTICE') }}
            </el-badge>
            <span v-else>{{ $t('SYSTEM_NOTICE') }}</span>
          </el-menu-item>
          <el-submenu index="themes" :popper-append-to-body="true" popper-class="user-menu">
            <template v-slot:title>{{ $t('THEME') }}</template>
            <el-menu-item
              v-for="item in dictList.THEME_LIST"
              :key="item.value"
              @click="setThemeFn(item.value)"
            >
              <i
                class="el-icon-check"
                :class="getTheme.toUpperCase().replace('-', '_') == item.value ? '' : 'opacity'"
              />
              {{ item.label }}
            </el-menu-item>
          </el-submenu>
          <el-submenu index="tab" :popper-append-to-body="true" popper-class="user-menu">
            <template v-slot:title>{{ $t('NAVIGATION_MODE') }}</template>
            <el-menu-item @click="setNav('hide-nav', $t('HIDDEN_DEFAULT'))">
              <i class="el-icon-check" :class="getTabsType == 'hide-nav' ? '' : 'opacity'" />
              {{ $t('HIDDEN_DEFAULT') }}
            </el-menu-item>
            <el-menu-item @click="setNav('breadcrumb-nav', $t('BREADCRUMB'))">
              <i class="el-icon-check" :class="getTabsType == 'breadcrumb-nav' ? '' : 'opacity'" />
              {{ $t('BREADCRUMB') }}
            </el-menu-item>
            <el-menu-item @click="setNav('tab-nav', $t('TAB_NAV'))">
              <i class="el-icon-check" :class="getTabsType == 'tab-nav' ? '' : 'opacity'" />
              {{ $t('TAB_NAV') }}
            </el-menu-item>
          </el-submenu>
          <el-submenu index="lang" :popper-append-to-body="true" popper-class="user-menu">
            <template v-slot:title>{{ $t('LANG') }}</template>
            <el-menu-item
              v-for="item in dictList.I18N_LOCALE"
              :key="item.value"
              @click="langSwitch(item.value)"
            >
              <i class="el-icon-check" :class="getLocale == item.value ? '' : 'opacity'" />
              {{ item.label }}
            </el-menu-item>
          </el-submenu>
          <el-menu-item @click="previewPDF">{{ $t('HELP') }}</el-menu-item>
          <el-menu-item @click="logout">{{ $t('LOG_OUT') }}</el-menu-item>
        </el-submenu>
      </el-menu>
    </div>
    <UserInfo :visible="infoShow" @close="infoShow = false" />
    <ModPwd :visible="pwdShow" @close="pwdShow = false" />
    <Auth :visible="authorizationShow" @close="authorizationShow = false" @gotAuth="gotAuth" />
  </div>
</template>
<script>
  import { mapGetters, mapMutations } from 'vuex'
  import Topbar from './Topbar'
  import UserInfo from './UserInfo'
  import ModPwd from './ModPwd'
  import Auth from './Auth'
  import SystemApi from '@/api/SystemApi'
  import OperateLogApi from '@/api/system/OperateLogApi.js'
  export default {
    components: { ModPwd, UserInfo, Topbar, Auth },
    data() {
      return {
        pwdShow: false,
        infoShow: false,
        authorizationShow: false,
        licenseValidDays: '',
        showIot: false
      }
    },
    computed: {
      ...mapGetters([
        'getMenu',
        'dictMap',
        'dictList',
        'getUserId',
        'getUser',
        'avatarData',
        'getSysNoticeCount',
        'getIsInitialPwd',
        'getRoles',
        'getTabsType',
        'getTheme',
        'getLocale',
        'notifyList'
      ]),
      defaultAvatar() {
        return this.avatarData
          ? this.avatarData.avatarData
          : require('@/assets/img/default_avatar.png')
      }
    },
    watch: {
      getRoles(val) {
        if (val.length) { this.getIot() }
      }
    },
    created() {
      if (this.getRoles && this.getRoles.length) { this.getIot() }
      this.$nextTick(() => {
        this.pwdShow = this.getIsInitialPwd
      })
      this.langSwitch(localStorage.lang || this.getLocale)
    },
    methods: {
      ...mapMutations([
        'clearInfo',
        'clearMenu',
        'setDict',
        'setTheme',
        'clearRegion'
      ]),
      previewPDF: () => {
        const url = `/res/光配机平台操作说明.pdf`
        window.open(url, '_blank')
      },
      getIot() {
        SystemApi.menu({
          sysId: 'AFS_IOT',
          roleIds: this.getRoles
        }).then(menu => {
          if (menu && menu.length) {
            this.showIot = true
          }
        })
      },
      // 权限信息更新
      gotAuth(data) {
        this.licenseValidDays = ''
        // 已授权
        if (data.effect) {
          const now = new Date().getTime()
          const startDay = new Date(data.effectDate).getTime()
          // 未到生效日期不判断
          if (now < startDay) return
          // 生效未过期，判断30天给出提示
          const difference = parseInt((now - startDay) / 3600 / 1000 / 24)
          const lastDays = data.validDays - difference
          if (lastDays <= 30) {
            this.licenseValidDays = this.$t('LICENSE_WILL_EXPIRES', { msg: lastDays })
          }
          if (lastDays < 0) {
            this.licenseValidDays = this.$t('AUTHORIZATION_HAS_EXPIRED')
          }
        } else {
          this.licenseValidDays = this.$t('LICENSE_STATUS_UNAUTHORIZED')
        }
      },
      logout() {
        this.$confirm(this.$t('CONFIRM_EXIT'), this.$t('EXIT_SYSTEM'), {
          type: 'warning'
        })
          .then(async() => {
            // 记录登出日志
            try {
              await OperateLogApi.addLog({
                api: '/authen/logout',
                item: 'LOG_OUT', // 退出登录
                terminal: 'LOG_OUT', // 退出登录
                operateResult: true,
                object: '/',
                realName: this.getUser.realName,
                content: JSON.stringify({
                  currentUserId: this.getUserId,
                  i18nKey: 'LOG_OUT_LOG'
                })
              })
            } catch (error) {
              console.log(error)
            }
            await SystemApi.logout().then(result => {
              localStorage.removeItem('token')
              this.clearInfo()
              this.clearMenu()
              this.clearRegion()
              this.$router.replace('/login')
              location.reload()
            })
          })
          .catch({})
      },
      handleSelect(key, keyPath) {
        console.log(key, keyPath)
      },
      iot() {
        localStorage.setItem('OEN_CUR_ROUTENAME', this.$route.path)
        localStorage.setItem('notifyList', JSON.stringify(this.notifyList))
        localStorage.setItem('changeSystem', true)
        location.href = '../iot'
      },
      langSwitch(lang) {
        this.$i18n.locale = lang
        this.$store.commit('SETLOCALE', lang)
        localStorage.setItem('lang', lang)
        document.title = this.$config.sysName[this.$i18n.locale] + '-' + this.$config.systemVersion
        this.setDict()
      },
      /**
       * 使用此方法设置主题
       */
      // 默认主题

      setThemeFn(themeName) {
        // console.log(themeName)
        themeName = themeName.toLowerCase().replace('_', '-')
        // console.log(themeName)
        localStorage.currentTheme = themeName
        this.setTheme(themeName)
        document.body.setAttribute('data-theme', themeName)
      },
      setNav(tabType, tabName) {
        // 设置导航模式
        // console.log(tabType)
        this.$store.commit('setTabType', tabType)
        localStorage.currentNavtype = tabType
      }
    }
  }
</script>
<style lang="scss">
  @import 'src/assets/css/mixin.module';
  .main-header {
    height: 100%;
    .logo {
      width: 20%;
      height: 100%;
      padding: 0 2% 20px 15px;
      background-size: 100% 100%;
      cursor: pointer;
      .sysLogo {
        background-size: 70%;
        height: 100%;
        min-width: 100px;
      }
    }
    .home_btn,
    .device_btn {
      width: 133px;
      height: 35px;
      line-height: 35px;
      font-size: 16px;
      text-align: center;
      background-position: center;
      background-repeat: no-repeat;
      background-size: 100%;
      @include themeify {
        color: themed('menuFontColor');
      }
    }
    .home_btn {
      background-size: 100% 100%;
      @include themeify {
        background-image: url(themed('menuHomeBtnBg'));
      }
      &.homeActive {
        color: #fff;
        @include themeify {
          background-image: url(themed('menuHomeBtnBgActive'));
        }
      }
    }
    .device_btn {
      margin-left: 9%;
      cursor: pointer;
      background-size: 100% 100%;
      @include themeify {
        background-image: url(themed('menuDeviceBtnBg'));
      }
    }
    .userinfo {
      width: 20%;
      height: 100%;
      float: right;
      background-size: 100% 100%;
      .el-avatar {
        @include themeify {
          background: themed('mainColor');
        }
      }
      .el-menu--horizontal > .el-menu-item {
        height: 100%;
        padding: 0;
      }
      .user-menu {
        float: right;
        margin-right: 20px;
        width: auto;
        .user-menu-item1 {
          .el-submenu__title {
            padding: 0;
          }
        }
        .user-menu-item2 {
          &:hover {
            background: none;
          }
        }
        .user-menu-item2.is-active {
          border: none;
        }
      }
      .sys-notice {
        position: absolute;
        left: 20px;
        top: -8px;
      }
    }
    .main-nav {
      flex: 1;
      height: 100%;
      background-size: 100% 100%;
      overflow: hidden;
      display: flex;
      justify-content: center;
      > .el-menu {
        height: 60px;
        .el-submenu__title i {
          color: #fff;
        }
      }
    }

    .el-menu--horizontal > .el-submenu .el-submenu__title,
    .el-menu--horizontal > .el-menu-item,
    .el-menu--horizontal > .el-submenu .el-submenu__title i {
      background-color: transparent !important;
      font-size: 16px;
      @include font_color('menuFontColor');
    }
    .el-menu--horizontal > .el-submenu .el-submenu__title {
      padding: 0;
      margin: 0 20px;
    }
    .el-menu--horizontal > .el-submenu.is-active .el-submenu__title,
    .el-menu--horizontal > .el-submenu.is-active .el-submenu__title i {
      @include font_color('menuFontColorActive');
    }
    .el-menu.el-menu--horizontal {
      border-bottom: 0;
      background-color: transparent !important;
      flex: 1;
      display: flex;
    }
    .user-name {
      margin-left: 5px;
      display: inline-block;
      max-width: 120px;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .license-expires {
      position: absolute;
      color: red;
      top: 25px;
      font-size: 10px;
    }
  }
  .el-menu--horizontal.main-header .el-menu .el-menu-item,
  .el-menu--horizontal.main-header .el-menu .el-submenu__title,
  .el-menu .el-menu-item i {
    color: #fff;
  }
  .el-menu--horizontal.main-header .el-menu-item:not(.is-disabled):focus,
  .el-menu--horizontal.main-header .el-menu-item:not(.is-disabled):hover {
    color: #fff;
  }
  .el-menu .el-menu-item .opacity {
    opacity: 0;
  }
  .el-submenu.is-active .el-submenu__title {
    border-bottom-color: transparent !important;
    border-image: linear-gradient(
        90deg,
        transparent 0%,
        rgba(255, 255, 255, 1) 50%,
        transparent 100%
      )
      2 2 2 2;
  }
</style>
